<script setup>
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";
import api from "@/api/api.js";
import { showDialog } from "vant";
import { useUserStore } from "@/stores/user.store";
import { storeToRefs } from "pinia";

const { userData } = storeToRefs(useUserStore());
const route = useRoute();

// 响应式数据
const enrollId = ref(route.query.id); //每项活动的id
const enrollPrice = ref(0); //每项活动报名费
const stepActive = ref(1); //步骤，1填写资料，2报名缴费，3线下复核，4完成报名
const isReg = ref(0); //是否填写资料，0未填写，1已填写
const payStatus = ref(0); //是否缴费，0未缴费，1已缴费，2退款，3无需退款
const status = ref(0); //是否复核，0未复核，1已复核
// 表单数据
const name = ref("");
const phone = ref("");
const cardno = ref("");
const place = ref("");

// 学历相关
const degrees = ref("");
const show_degrees = ref(false);
const degrees_list = ref([]);

// 工种相关
const work = ref("");
const show_work = ref(false);
const work_list = ref([]);

// 等级相关
const level = ref("");
const show_level = ref(false);
const level_list = ref([]);

const id = ref("");

// 获取报名信息
const get_EnrollInfo = async () => {
  const res = await api.getEnrollInfo({ id: id.value });
  isReg.value = res.isReg;

  if (isReg.value === 1) {
    // 填充已有的数据
    name.value = res.name;
    phone.value = res.phone;
    cardno.value = res.cardno;
    place.value = res.place;
    degrees.value = res.option1;
    work.value = res.option2;
    level.value = res.option3;
    enrollPrice.value = res.price;
    stepActive.value = res.step;
    payStatus.value = res.payStatus;
    status.value = res.status;

    // 获取下拉选项数据
    const [degreesRes, workRes, levelRes] = await Promise.all([
      api.zcjs_get({ id: id.value, type: "option1" }),
      api.zcjs_get({ id: id.value, type: "option2" }),
      api.zcjs_get({ id: id.value, type: "option3", option: work.value }),
    ]);

    degrees_list.value = degreesRes.map((item, index) => ({
      text: item,
      value: index + 1,
    }));
    work_list.value = workRes.map((item, index) => ({
      text: item,
      value: index + 1,
    }));
    level_list.value = levelRes.map((item, index) => ({
      text: item,
      value: index + 1,
    }));
  }
};

// 获取学历选项
const getDegrees = async () => {
  const res = await api.zcjs_get({ id: id.value, type: "option1" });
  degrees_list.value = res.map((item, index) => ({
    text: item,
    value: index + 1,
  }));
};
// getDegrees();

// 获取工种选项
const getWork = async () => {
  const res = await api.zcjs_get({ id: id.value, type: "option2" });
  work_list.value = res.map((item, index) => ({
    text: item,
    value: index + 1,
  }));
};
// getWork();

// 学历确认
const onDegreesConfirm = ({ selectedOptions }) => {
  show_degrees.value = false;
  degrees.value = selectedOptions[0]?.text;
};

// 工种确认
const onWorkConfirm = async ({ selectedOptions }) => {
  if (status.value === 0) {
    show_work.value = false;
    work.value = selectedOptions[0]?.text;
    // 重置等级
    level.value = "";
    level_list.value = [];

    const res = await api.zcjs_get({
      id: id.value,
      type: "option3",
      option: work.value,
    });
    level_list.value = res.map((item, index) => ({
      text: item,
      value: index + 1,
    }));
  }
};

// 等级确认
const onLevelConfirm = ({ selectedOptions }) => {
  if (status.value === 0) {
    show_level.value = false;
    level.value = selectedOptions[0]?.text;
  }
  getPrice();
};

// 获取价格
const getPrice = async () => {
  if (degrees.value && work.value && level.value) {
    const params = { id: id.value, type: "price", option: level.value };
    enrollPrice.value = await api.zcjs_get(params);
  }
};

// 提交表单
const onSubmit = async (values) => {
  if (status.value === 0) {
    const enrollForm = { ...values, id: id.value };
    const res = await api.zcjs_submit(enrollForm);
    if (res === "报名信息提交成功") dialog_show.value = true;
  }
};

// 弹窗相关
const dialog_show = ref(false);

const toPay = async () => {
  const params = {
    id: enrollId.value,
    redirectUrl: "",
    backUrl: "",
  };
  const res = await api.postPay(params);
  window.location.href = res.url;
  dialog_show.value = false;
};

// 组件挂载时
onMounted(async () => {
  id.value = route.query.id;
  getDegrees();
  getWork();
  if (userData.value) {
    name.value = userData.value.name;
    phone.value = userData.value.phone;
    cardno.value = userData.value.cardno;
    await get_EnrollInfo();
  }

  // 缴费成功提示
  if (payStatus.value === 1) {
    showDialog({
      title: "您已缴费成功！",
      message: "请保持电话畅通，耐心等待工作人员联系。",
    });
  }

  // 报名完成提示
  if (stepActive.value === 4) {
    showDialog({
      title: "您已报名成功！",
      message: "请保持电话畅通，耐心等待工作人员联系。",
    });
  }
});
</script>

<template>
  <div class="enroll-container">
    <van-nav-bar title="填写报名信息" style="margin: 20px 0" />
    <main>
      <van-form class="form" @submit="onSubmit">
        <!-- 姓名 -->
        <van-field
          class="field-box"
          v-model="name"
          name="name"
          input-align="center"
          :style="{ color: status === 1 ? '#c8c9d6' : 'black' }"
          :readonly="status === 1"
          placeholder="请填写您的真实姓名"
        />

        <!-- 手机号 -->
        <van-field
          class="field-box"
          v-model="phone"
          name="phone"
          input-align="center"
          placeholder="请填写本人的手机号"
          :style="{ color: status === 1 ? '#c8c9d6' : 'black' }"
          :readonly="status === 1"
        />

        <!-- 身份证 -->
        <van-field
          class="field-box"
          v-model="cardno"
          name="cardno"
          input-align="center"
          :readonly="status === 1"
          :style="{ color: status === 1 ? '#c8c9d6' : 'black' }"
          placeholder="请填写本人的身份证号"
        />

        <!-- 单位名称 -->
        <div class="field-box">
          <p>请填写本人就职的单位名称</p>
          <van-field
            class="place"
            v-model="place"
            name="place"
            input-align="center"
            :readonly="status === 1"
            :style="{ color: status === 1 ? '#c8c9d6' : 'black' }"
            placeholder="（若暂无就职单位可写无单位）"
          />
        </div>

        <!-- 最高学历 -->
        <van-field
          is-link
          class="field-box"
          v-model="degrees"
          arrow-direction="down"
          name="option1"
          readonly
          :disabled="status === 1"
          placeholder="请选择您的最高全日制学历"
          @click="show_degrees = true"
        />
        <van-popup v-model:show="show_degrees" position="bottom">
          <van-picker
            :columns="degrees_list"
            @confirm="onDegreesConfirm"
            @cancel="show_degrees = false"
          />
        </van-popup>

        <!-- 工种名称 -->
        <van-field
          is-link
          class="field-box"
          v-model="work"
          arrow-direction="down"
          name="option2"
          readonly
          :disabled="status === 1"
          placeholder="请选择工种名称"
          @click="show_work = true"
        />
        <van-popup v-model:show="show_work" position="bottom">
          <van-picker
            :columns="work_list"
            @confirm="onWorkConfirm"
            @cancel="show_work = false"
          />
        </van-popup>

        <!-- 等级 -->
        <van-field
          is-link
          class="field-box"
          v-model="level"
          arrow-direction="down"
          name="option3"
          readonly
          :disabled="status === 1"
          placeholder="请选择等级"
          @click="show_level = true"
        />
        <van-popup v-model:show="show_level" position="bottom">
          <van-picker
            :columns="level_list"
            @confirm="onLevelConfirm"
            @cancel="show_level = false"
          />
        </van-popup>

        <div style="margin: 100px 15px">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :disabled="status === 1"
            style="background-color: #4b79e3"
          >
            {{
              payStatus === 1
                ? "已报名"
                : enrollPrice === 0
                ? "确认提交"
                : `前往缴费（￥${enrollPrice}）`
            }}
          </van-button>
        </div>
      </van-form>
    </main>

    <van-dialog
      v-model:show="dialog_show"
      title="填写报名信息成功"
      confirmButtonText="前往缴付"
      @confirm="toPay"
    >
      <van-icon class="icon" name="success" color="#3b8af8" size="30" />
    </van-dialog>
  </div>
</template>

<style scoped lang="less">
@import url("@/styles/enroll/enroll_zcjn");
</style>
